<template>
  <div class="app-container">
    <div style="padding: 20px;">
      <el-row>
        <el-col :span="4">
          <strong style="font-size: 20px;">
            新增/修改
          </strong>
        </el-col>
      </el-row>

      <div style="padding:20px">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="form.username" :disabled="disabled" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.plainPassword" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select
              v-model="form.type"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in types"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否激活">
            <el-checkbox v-model="form.enabled" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: Number(this.$route.params.id),
      store: '',
      types: [
        { label: '收银', value: 'cashier' },
        { label: '财务', value: 'finance' },
        { label: '人事', value: 'personnel' },
        { label: '考勤', value: 'attendance' }
      ],
      form: {
        username: '',
        plainPassword: '',
        type: null,
        enabled: true
      },
      disabled: false
    }
  },
  created() {
    this.store = localStorage.getItem('storeId')
    if (this.id) {
      this.disabled = true
      if (this.store > 0) {
        this.axios.get(`/store/${this.store}/officers/${this.id}`, { params: {
          '@expands': `['entity.user']`
        }}).then((res) => {
          this.form.userId = res.data.user.id
          this.form.type = res.data.type
          this.form.username = res.data.user.__metadata.username
          this.form.enabled = res.data.enabled
        })
      }
    }
  },
  methods: {
    onSubmit() {
      if (this.store > 0) {
        if (!this.form.type) {
          this.$message.error('请选择账号类型！')
          return
        }
        const roles = ['ROLE_USER']
        if (this.form.type === 'finance') {
          roles.push('ROLE_FINANCE')
        } else if (this.form.type === 'personnel') {
          roles.push('ROLE_PERSONNEL')
        } else if (this.form.type === 'cashier') {
          roles.push('ROLE_CASHIER')
        } else if (this.form.type === 'attendance') {
          roles.push('ROLE_ATTENDANCE')
        }

        if (this.id) {
          const loading = this.$loading({
            lock: true,
            text: '数据交互中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          if (this.form.plainPassword) {
            this.axios.put(`/store/${this.store}/users/${this.form.userId}/change-password`, { password: this.form.plainPassword })
          }
          this.axios.put(`/store/${this.store}/users/${this.form.userId}`, {
            roles: roles
          }).then((update) => {
            this.axios.put(`/store/${this.store}/officers/${this.id}`, {
              type: this.form.type,
              enabled: this.form.enabled
            }).then((res) => {
              this.$message.success('修改成功！')
              this.$router.go(-1)
              loading.close()
            })
          })
        } else {
          if (!this.form.username) {
            this.$message.error('请填写用户名！')
            return
          }
          if (this.form.username === 'admin' || this.form.username === 'platform') {
            this.$message.error('禁用名！')
            return
          }
          if (!this.form.plainPassword) {
            this.$message.error('请填写密码！')
            return
          }

          const loading = this.$loading({
            lock: true,
            text: '数据交互中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.axios.get(`/store/${this.store}/users`, { params: {
            '@filter': `entity.getUsername() == "${this.form.username}"`
          }}).then((res) => {
            if (res.data.length > 0) {
              const user = res.data[0]
              if (!user.enabled) {
                loading.close()
                this.$message.error('此用户名账号已停用！')
                return
              }
              if (user.officer) {
                loading.close()
                this.$message.error('此用户名已建立账号信息！')
                return
              }

              this.axios.put(`/store/${this.store}/users/${user.id}`, {
                roles: roles
              }).then((update) => {
                this.axios.post(`/store/${this.store}/officers`, {
                  user: user.id,
                  type: this.form.type,
                  enabled: this.form.enabled
                }).then(officer => {
                  loading.close()
                  this.$message.success('修改成功！')
                  this.$router.go(-1)
                })
              })
            } else {
              this.axios.post(`/store/${this.store}/users`, {
                username: this.form.username,
                email: this.form.username + '@email.com',
                enabled: true,
                roles: roles,
                plainPassword: this.form.plainPassword
              }).then(user => {
                this.axios.post(`/store/${this.store}/officers`, {
                  user: user.data.id,
                  type: this.form.type,
                  enabled: this.form.enabled
                }).then(officer => {
                  loading.close()
                  this.$message.success('修改成功！')
                  this.$router.go(-1)
                })
              })
            }
          })
        }
      }
    }
  }
}
</script>
